package com.example.wifi_demo;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.wifi_demo.databinding.ActivityMainBinding;
import com.google.gson.Gson;

import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
//    private String access_token = "80_9t4tuGsLrcijTv9OPUy-k8vzURLYyVXAE4fsl_RQhiYum-pFk0nwz600bkAAhwbo7v3e3irxFv3PcayG7Z6brMi_4bHdP2PuKkJzfAA1CPbjZv7faZcxUjpRPooDZAjAGAMIJ";
    private String access_token;
    private String pageUrl = "pages/index/index?";
    private String httpPostUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
    private String httpGetUrl = "https://api.weixin.qq.com/cgi-bin/token";
    private String postAddUserInfo = "https://ami.miqimini.com/addUserInfo";
    private String shopName;
    private boolean isBitmap = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Map<String,String> map = new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid","wx4dd6cc3245a1ce60");
        map.put("secret","44e121ccfde07a5eb86b1e64570c8254");
        OkhtttpUtils.getInstance().doGet(this, httpGetUrl, map, new OkhtttpUtils.OkCallback() {
            @Override
            public void onFailure(Exception e) {
                Log.e("psq",e.getMessage().toString());
            }

            @Override
            public void onResponse(String json) {
                Log.e("psq",json);
                JsonBean jsonBean = new Gson().fromJson(json,JsonBean.class);
                access_token = jsonBean.getAccess_token();
            }

            @Override
            public void onImageResponse(Bitmap bitmap) {

            }
        });

        binding.btnCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isBitmap = false;
                shopName = binding.edtShopName.getText().toString().toString();
                String name = binding.edtName.getText().toString().toString();
                String address = binding.edtAddress.getText().toString().trim();
                String bankCard = binding.edtBankCard.getText().toString().toString();
                String wifiAccount = binding.edtWifiSsid.getText().toString().trim();
                String password = binding.edtWifiPsw.getText().toString().trim();
                String reference = binding.edtReference.getText().toString().trim();
                try {
                    Map<String, Object> keyMap = RSAUtils.initKey();
                    // 获取公钥字符串
                    String publicKey = RSAUtils.getPublicKeyStr(keyMap);
                    // 获取私钥字符串
                    String privateKey = RSAUtils.getPrivateKeyStr(keyMap);
                    String str = shopName+"&"+address+"&"+name+"&"+bankCard+"&"+wifiAccount+"&"+password+"&"+reference;
                    String encrypt = RSAUtils.encrypt(str.getBytes(), publicKey);
                    Log.e("psq","加密：" + encrypt);
                    postAddUserInfo(encrypt,privateKey,shopName,wifiAccount,password);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
        });

        binding.btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isBitmap){
                    binding.lin.post(new Runnable() {
                        @Override
                        public void run() {
                            Bitmap bitmap = captureView(binding.lin);
                            saveBitmapToGallery(MainActivity.this, bitmap, "MyCapturedImage");
                        }
                    });
                }
            }
        });

        binding.iv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.edtShopName.setText("");
            }
        });

        binding.iv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.edtAddress.setText("");
            }
        });

        binding.iv3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.edtName.setText("");

            }
        });

        binding.iv4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.edtBankCard.setText("");

            }
        });

        binding.iv5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.edtWifiSsid.setText("");

            }
        });

        binding.iv6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.edtWifiPsw.setText("");
            }
        });

        binding.iv6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.edtReference.setText("");
            }
        });
    }

    public void postAddUserInfo(String encrypt,String privateKey,String shopName,String wifiAccount,String password){
        Map<String,String> map = new HashMap<>();
        map.put("encrypt",encrypt);
        map.put("privateKey",privateKey);
        OkhtttpUtils.getInstance().doPost(this,postAddUserInfo,map, new OkhtttpUtils.OkCallback() {
            @Override
            public void onFailure(Exception e) {
                Log.e("psq",e.getMessage().toString());
            }

            @Override
            public void onResponse(String json) {
                Log.e("psq",json);
                try {
                    User user = new Gson().fromJson(json,User.class);
                    post(shopName,wifiAccount,password,user.data.getId());
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

            }

            @Override
            public void onImageResponse(Bitmap bitmap) {
                Log.e("psq","onImageResponse");
            }
        });
    }

    public void post(String shopName,String wifiAccount,String password,int id) throws JSONException {
        ParmBean parmBean = new ParmBean();
        parmBean.setPath(pageUrl+ "?id="+id +"&wifiAccount=" + wifiAccount +"&wifiPassword=" + password + "&shopName=" + shopName);
        parmBean.setEnv_version("release");//trial 体验 release 正式
        parmBean.setWidth("200");
        OkhtttpUtils.getInstance().doPost(this,httpPostUrl+access_token,new Gson().toJson(parmBean), new OkhtttpUtils.OkCallback() {
            @Override
            public void onFailure(Exception e) {
                Log.e("psq",e.getMessage().toString());
            }

            @Override
            public void onResponse(String json) {
                Log.e("psq",json);
            }

            @Override
            public void onImageResponse(Bitmap bitmap) {
                Log.e("psq","onImageResponse");
                binding.ivQrcode.setImageBitmap(bitmap);
                binding.tvShopName.setText("商铺名："+shopName);
                isBitmap = true;
            }
        });
    }

    /**
     * 截图某个控件
     * @param view 要截图的控件
     * @return 截图生成的 Bitmap
     */
    private Bitmap captureView(View view) {
        // 创建与控件尺寸相同的Bitmap
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        // 创建画布并将Bitmap关联
        Canvas canvas = new Canvas(bitmap);
        // 将控件内容绘制到画布上
        view.draw(canvas);
        return bitmap;
    }

    /**
     * 将 Bitmap 保存到相册中
     * @param context 上下文
     * @param bitmap 要保存的 Bitmap
     * @param title 图片的标题
     */
    private void saveBitmapToGallery(Context context, Bitmap bitmap, String title) {
        OutputStream fos;
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DISPLAY_NAME, title + ".jpg");
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

                Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                if (uri != null) {
                    fos = context.getContentResolver().openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    if (fos != null) {
                        fos.close();
                    }
                    Toast.makeText(context, "图片已保存到相册", Toast.LENGTH_SHORT).show();
                }
            } else {
                File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                if (!directory.exists()) {
                    directory.mkdirs();
                }
                File file = new File(directory, title + ".jpg");
                fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.close();

                // 将文件插入到系统图库
                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), title, null);
                // 通知图库更新
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

                Toast.makeText(context, "图片已保存到相册", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "保存图片失败", Toast.LENGTH_SHORT).show();
        }
    }
}